import { defineStore } from 'pinia'
import commentAPI from '../api/comment'

export const useCommentStore = defineStore('comment', {
  state: () => ({
    comments: [],
    loading: false,
    error: null,
    totalComments: 0
  }),

  getters: {
    // 获取某个文章的评论列表
    getCommentsByArticleId: (state) => (articleId) => {
      return state.comments.filter(comment => String(comment.articleId) === String(articleId))
    },

    // 获取顶级评论（parentId为0的评论）
    getTopLevelComments: (state) => (articleId) => {
      return state.getCommentsByArticleId(articleId).filter(comment => comment.parentId === 0)
    },

    // 获取评论的回复
    getReplies: (state) => (parentId) => {
      return state.comments.filter(comment => String(comment.parentId) === String(parentId))
    }
  },

  actions: {
    // 根据文章ID获取评论列表
    async fetchCommentsByArticleId(articleId) {
      this.loading = true
      this.error = null
      try {
        // 将ID转换为数字类型
        const numericId = typeof articleId === 'string' ? Number(articleId) : articleId
        const response = await commentAPI.getCommentsByArticleId(numericId)
        if (response.code === 200) {
          this.comments = response.data
          this.totalComments = response.data.length
          return response.data
        } else {
          throw new Error(response.message || '获取评论列表失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 创建评论
    async createComment(commentData) {
      this.loading = true
      this.error = null
      try {
        const response = await commentAPI.createComment(commentData)
        if (response.code === 200) {
          // 添加到本地评论列表
          this.comments.push(response.data)
          this.totalComments++
          return response.data
        } else {
          throw new Error(response.message || '创建评论失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 删除评论
    async deleteComment(id) {
      this.loading = true
      this.error = null
      try {
        // 将ID转换为数字类型
        const numericId = typeof id === 'string' ? Number(id) : id
        const response = await commentAPI.deleteComment(numericId)
        if (response.code === 200) {
          // 从本地评论列表中移除
          this.comments = this.comments.filter(comment => String(comment.id) !== String(id))
          this.totalComments--
          return true
        } else {
          throw new Error(response.message || '删除评论失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 获取所有评论（管理功能）
    async fetchAllComments() {
      this.loading = true
      this.error = null
      try {
        const response = await commentAPI.getCommentList()
        if (response.code === 200) {
          this.comments = response.data
          this.totalComments = response.data.length
          return response.data
        } else {
          throw new Error(response.message || '获取评论列表失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 更新评论状态
    async updateCommentStatus(id, status) {
      this.loading = true
      this.error = null
      try {
        // 将ID转换为数字类型
        const numericId = typeof id === 'string' ? Number(id) : id
        const response = await commentAPI.updateCommentStatus(numericId, status)
        if (response.code === 200) {
          // 更新本地评论状态
          const index = this.comments.findIndex(comment => String(comment.id) === String(id))
          if (index !== -1) {
            this.comments[index].status = status
          }
          return response.data
        } else {
          throw new Error(response.message || '更新评论状态失败')
        }
      } catch (error) {
        this.error = error.message
        throw error
      } finally {
        this.loading = false
      }
    },

    // 清空评论数据
    clearComments() {
      this.comments = []
      this.totalComments = 0
      this.error = null
    }
  }
})